package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.HttpStatus;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.form.OrderForm;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.order.vo.TradeVo;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.RemoteSkuStockService;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuLockVo;
import com.spzx.product.api.domain.SkuPriceVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author biu
 * @since 2025-03-18
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired
    private RemoteCartService  remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RemoteProductService remoteProductService;


    @Autowired
    private RemoteSkuStockService remoteSkuStockService;

    @Autowired
    private RabbitService rabbitService;


    @Override
    public TradeVo orderTradeData() {
        R<List<CartInfo>> cartCheckedListResult = remoteCartService.getCartCheckedList(SecurityConstants.INNER);
        if (R.FAIL == cartCheckedListResult.getCode()) {
            throw new ServiceException(cartCheckedListResult.getMsg());
        }
        List<CartInfo> cartCheckedList = cartCheckedListResult.getData();
        if (CollectionUtils.isEmpty(cartCheckedList)) {
            throw new ServiceException("没有选中任何商品");
        }

        //判断价格是否变化 TODO

        //封装List<OrderItem> orderItemList
        List<OrderItem> orderItemList = cartCheckedList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            return orderItem;
        }).toList();

        //计算商品总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setTradeNo(generateTradeNo());
        tradeVo.setIsBuy(false); //从购物车中点击“结算"提交过来

        return tradeVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submitOrder(OrderForm orderForm) {

        //获取用户id
   //1 防止订单重复提交&防止页面停留超时
        //当订单在购物车中点击就算的时候，redis就已经存了订单号了
        //判断订单号是否存在：
// 如果存在则说明用户第一次提交此订单
// 如果五分中内提交了第二次订单，则订单号不存在，则说明用户已经提交过该订单，不能重复提交
// 如果五分中之后第一次提交，则订单号也不存在，说明操作超时

        Long userId = SecurityUtils.getUserId();


        String userTradeKey = "user:tradeNo:" + userId;
// 将键的值更为 processed  表示已处理
// return 1 表示处理成功
// return -1  键存在但值不匹配，表示重复提交
// return 0   键不存在，订单过期
        String scriptText = """
	if redis.call('get', KEYS[1]) == ARGV[1] then
        redis.call('set', KEYS[1], 'processed', 'ex', ARGV[2])
        return 1
    else
    	if redis.call('exists', KEYS[1]) == 1 then
            return -1
        else
        	return 0
        end
    end
	""";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        Long flag = (Long)redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), orderForm.getTradeNo(), 3);
        if (flag == 0) {
            throw new ServiceException("操作超时，请退回重试");
        }
        if(flag == -1){
            throw new ServiceException("请勿重复提交订单" + HttpStatus.SUBMIT_REPEATE);
        }






        //2 判断价格是否改变并更新购物车中的商品价格
        // 2.1 批量获取商品实时价格 TODO
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).collect(Collectors.toList());
        R<List<SkuPriceVo>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if(R.FAIL == skuPriceListResult.getCode()){
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPriceVo> skuPriceVoList = skuPriceListResult.getData();
        // 2.2 并判断价格是否变更 TODO

         /*orderItemList   n
        skuPriceVoList  n*/
        /*for (OrderItem orderItem : orderItemList) {
            for (SkuPriceVo skuPriceVo : skuPriceVoList) {
                if(orderItem.getSkuPrice().compareTo(skuPriceVo.getSalePrice()) != 0){
                    //价格发生了变化
                }
            }
        }*/


        // 2.3 如果有变更，则更新购物车中的商品价格 TODO
        String priceCheckResult = "";
        //将列表转换成hashmap O(n)
        Map<Long, BigDecimal> skuPriceMap = skuPriceVoList.stream().collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice));
        // O(n)
        for (OrderItem orderItem : orderItemList) {
            if(skuPriceMap.get(orderItem.getSkuId()).compareTo(orderItem.getSkuPrice()) != 0){
                //价格发生了变化
                priceCheckResult += orderItem.getSkuName() + "\n";
            }
        }

        //价格有变化 且  不是立即购买（经过了购物车）
        if(StringUtils.hasText(priceCheckResult) && !orderForm.getIsBuy()){
            //更新购物车中的商品价格
            R<Boolean> updateCarPriceResult = remoteCartService.updateCartPrice(SecurityConstants.INNER);
            if (R.FAIL == updateCarPriceResult.getCode()) {
                throw new ServiceException("更新购物车商品价格失败：" + updateCarPriceResult.getMsg());
            }

            //中止下单
            throw new ServiceException("价格有变化，请重新下单：\n" + priceCheckResult);
        }

        //3 校验库存并锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuName(orderItem.getSkuName());
            return skuLockVo;
        }).toList();
        R<String> stringResult = remoteSkuStockService.checkAndLock(
                orderForm.getTradeNo(),
                skuLockVoList,
                SecurityConstants.INNER);
        if(R.FAIL == stringResult.getCode()){
            throw new ServiceException("远程调用失败：" + stringResult.getMsg());
        }
        String resultMessage = stringResult.getData();
        if(StringUtils.hasText(resultMessage)){
            throw new ServiceException(resultMessage);
        }


        //4 下单
        Long orderId = null;
        try {
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_PRODUCT,
                    MqConst.ROUTING_UNLOCK,
                    orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }


        //5 删除购物车选中商品
        if(!orderForm.getIsBuy()){
            R<Boolean> deleteResult = remoteCartService.deleteCartCheckedList(SecurityConstants.INNER);
            if (R.FAIL == deleteResult.getCode()) {
                log.error(deleteResult.getMsg());
                //非核心流程不影响程序的执行
                //throw new ServiceException(deleteResult.getMsg());
            }
        }

        return orderId;
    }


    @Override
    public TradeVo buy(Long skuId) {
        R<ProductSkuVo> productSkuVoResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSkuVoResult.getCode()) {
            throw new ServiceException("远程调用失败-buy接口" + productSkuVoResult.getMsg());
        }
        ProductSkuVo productSkuVo = productSkuVoResult.getData();
        ArrayList<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSkuVo.getSkuName());
        orderItem.setThumbImg(productSkuVo.getThumbImg());
        orderItem.setSkuPrice(productSkuVo.getSalePrice());
        orderItem.setSkuNum(1);
        orderItemList.add(orderItem);

        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(productSkuVo.getSalePrice());
        tradeVo.setIsBuy(true);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(generateTradeNo());

        return tradeVo;
    }

    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(orderStatus != null,OrderInfo::getOrderStatus, orderStatus)
                .eq(OrderInfo::getUserId, SecurityUtils.getUserId())
                .orderByDesc(OrderInfo::getCreateTime);

        //查询所有订单列表
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);

        //优化查询所有订单列表
        if(!CollectionUtils.isEmpty(orderInfoList)){
            LambdaQueryWrapper<OrderItem> queryWrapperItem = new LambdaQueryWrapper<>();
            queryWrapperItem.in(OrderItem::getOrderId, orderInfoList.stream().map(OrderInfo::getId).toList());
            List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapperItem);

            //将订单项列表根据订单id进行分组到相对应的订单对象中
            Map<Long, List<OrderItem>> listMap = orderItemList
                    .stream()
                    .collect(Collectors.groupingBy(OrderItem::getOrderId));

            for (OrderInfo orderInfo : orderInfoList) {
                orderInfo.setOrderItemList(listMap.get(orderInfo.getId()));
            }
        }
        return orderInfoList;
    }

    @Override
    public OrderInfo getOrderInfoById(Long orderId) {
        LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItem::getOrderId, orderId);// 查询当传来的orderID参数 “等于” 数据库中Order_id列的值

        List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(orderItemList)){
            OrderInfo orderInfo = baseMapper.selectById(orderId);
            orderInfo.setOrderItemList(orderItemList);
            return orderInfo;
        }
        return null;
    }


    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setId(orderId);
        orderInfo.setOrderStatus(-1);
        orderInfo.setCancelReason("七天无理由退货退款");
        orderInfo.setCancelTime(new Date());
        orderInfo.setUpdateBy(SecurityUtils.getUsername());  //更新者
       baseMapper.updateById(orderInfo);

        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setProcessStatus(-1);
        orderLog.setNote("用户取消订单");
        orderLogMapper.insert(orderLog);


        //处理库存
        OrderInfo order = baseMapper.selectById(orderId);
        rabbitService.sendMessage(
                MqConst.EXCHANGE_PRODUCT,
                MqConst.ROUTING_UNLOCK,
                order.getOrderNo());
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = baseMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));

        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));

        orderInfo.setOrderItemList(orderItemList);

        return orderInfo;

    }


    @Override
    public void proccessPayStatus(String orderNo) {
        OrderInfo orderInfo = baseMapper.selectOne(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getOrderNo, orderNo)
                );

        if(orderInfo != null && orderInfo.getOrderStatus() == 1){
            return;
        }
        orderInfo.setOrderStatus(1);
        orderInfo.setPaymentTime(new Date());
        baseMapper.updateById(orderInfo);

    }


    private Long saveOrder(OrderForm orderForm) {
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        // 保存订单记录：order_info
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setOrderNo(orderForm.getTradeNo());//订单号
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        orderInfo.setFeightFee(orderForm.getFeightFee());

        //远程调用获取用户地址信息
        R<UserAddress> userAddressResult = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER);
        if(R.FAIL == userAddressResult.getCode()){
            throw new ServiceException(userAddressResult.getMsg());
        }
        //获取用户地址信息
        UserAddress userAddress = userAddressResult.getData();
        //保存用户地址信息
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        //实时获取总价格
        //计算orderItem中商品的总价格
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = orderItemList
                .stream()
                .map(
                        orderItem -> orderItem
                                .getSkuPrice()
                                .multiply(new BigDecimal(orderItem.getSkuNum()))
                )
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        //设置商品总价格
        orderInfo.setOriginalTotalAmount(totalAmount);//原价
        orderInfo.setCouponAmount(new BigDecimal(0));//优惠券价格
        orderInfo.setTotalAmount(totalAmount);
        //订单状态
        orderInfo.setOrderStatus(0);//待付款

        orderInfo.setCreateBy(userName);
        orderInfo.setUpdateBy(userName);
        baseMapper.insert(orderInfo);

        // 保存订单项记录：order_item
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItem.setCreateBy(userName);
            orderItem.setUpdateBy(userName);
            orderItemMapper.insert(orderItem);
        }

        // 保存订单日志记录：order_log
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setOperateUser(userName);
        orderLog.setNote("提交订单");
        orderLog.setCreateBy(userName);
        orderLog.setUpdateBy(userName);
        orderLogMapper.insert(orderLog);

        return orderInfo.getId();
    }






    private String generateTradeNo() {
        Long userId = SecurityUtils.getUserId();
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.流水号value
        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        //3.将流水号放入redis，过期时间5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);

        return tradeNo;
    }


    /**
     * 验证页面提交流水号是否有效
     * @param userId
     * @param tradeNo
     * @return
     */
    private Boolean checkTradeNo(String tradeNo) {
        String userTradeKey = "user:tradeNo:" + SecurityUtils.getUserId();
        String redisTradeNo = (String) redisTemplate.opsForValue().get(userTradeKey);
        return tradeNo.equals(redisTradeNo);
    }

    /**
     * 删除流水号
     * @param userId
     */
    private void deleteTradeNo() {
        String userTradeKey = "user:tradeNo:" + SecurityUtils.getUserId();
        redisTemplate.delete(userTradeKey);
    }
}
